import SwiftUI
import SPGlassKit

public struct GlassChartExample: GlassExample {
    public static let componentID = "glass-chart"

    // Fictitious data: energy produced by two imaginary sites.
    private static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    private static let north: [Double] = [42, 48, 55, 61, 58, 70]
    private static let south: [Double] = [65, 60, 57, 52, 49, 44]

    private static let production: [GlassChartPoint] =
        zip(months, north).map { GlassChartPoint(label: $0, value: $1, series: "North") }
        + zip(months, south).map { GlassChartPoint(label: $0, value: $1, series: "South") }

    private static let visits: [GlassChartPoint] = {
        let start = Date(timeIntervalSince1970: 1_780_272_000)
        let values: [Double] = [120, 135, 128, 160, 190, 240, 210]
        return values.enumerated().map { GlassChartPoint(date: start.addingTimeInterval(Double($0.offset) * 86_400), value: $0.element) }
    }()

    @State private var kind = GlassChartKind.line
    @State private var series = "All"

    public init() {}

    private var visibleProduction: [GlassChartPoint] {
        series == "All" ? Self.production : Self.production.filter { $0.series == series }
    }

    public var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                Picker("Mark", selection: $kind) {
                    Text("Line").tag(GlassChartKind.line)
                    Text("Bar").tag(GlassChartKind.bar)
                    Text("Area").tag(GlassChartKind.area)
                }
                .pickerStyle(.segmented)

                GlassChart("Energy produced", points: visibleProduction, kind: kind, xAxisTitle: "Month", yAxisTitle: "Energy", unit: "MWh") {
                    Picker("Series", selection: $series) {
                        Text("All").tag("All")
                        ForEach(GlassChartLogic.seriesNames(Self.production), id: \.self) { Text(verbatim: $0).tag($0) }
                    }
                    .pickerStyle(.menu)
                }

                GlassChart("Daily visits", points: Self.visits, kind: .area, xAxisTitle: "Day", yAxisTitle: "Visits")

                GlassChart("Nothing measured yet", points: [])
            }
            .padding()
        }
    }
}

#Preview("GlassChart") { GlassChartExample().glassTheme(.ocean) }
